package com.ming_za.od_updater_sdk.utils;

import com.ming_za.od_updater_sdk.IUpdater;
import com.ming_za.od_updater_sdk.ODUpdater;
import com.ming_za.od_updater_sdk.obj.Res;
import com.ming_za.od_updater_sdk.transmit.IStreamTransmit;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtils {

    /**
     * 传输缓冲区大小
     */
    private final int MAX_BUFFER_SIZE;

    public FileUtils(int maxBufferSize) {
        MAX_BUFFER_SIZE = maxBufferSize;
    }

    /**
     * 传输文件
     * @param inputStream 输入流
     * @param outputStream 输出流
     * @param fileSize 文件总大小
     * @param res 更新资源对象
     * @throws IOException 传输时的IO异常
     */
    public void transmitFile(InputStream inputStream, OutputStream outputStream, long fileSize, Res res, IUpdater odUpdater) throws IOException {

        byte[] buffer = new byte[MAX_BUFFER_SIZE];
        int bytesRead;
        long totalBytesRead = 0;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            totalBytesRead += bytesRead;
            odUpdater.getIStreamTransmit().transmit(outputStream, buffer, bytesRead,odUpdater);
            odUpdater.getIStreamTransmit().postTransmit(totalBytesRead,fileSize,res,odUpdater);
        }
    }

}
